{% extends "base.html" %}

{% block title %}{% if user.role == 'admin' %}分享管理{% else %}我的分享{% endif %} - {{ app_name }}{% endblock %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2>
                    <i class="fas fa-share-alt me-2"></i>
                    {% if user.role == 'admin' %}分享管理{% else %}我的分享{% endif %}
                </h2>
                <div>
                    {% if user.role == 'admin' %}
                    <a href="/admin" class="btn btn-outline-secondary me-2">
                        <i class="fas fa-arrow-left me-2"></i>返回后台
                    </a>
                    <button type="button" class="btn btn-success" onclick="exportShares()">
                        <i class="fas fa-download me-2"></i>导出数据
                    </button>
                    {% endif %}
                </div>
            </div>

            <!-- 搜索和筛选 -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label for="searchInput" class="form-label">搜索</label>
                            <input type="text" class="form-control" id="searchInput" placeholder="搜索URL、账号{% if user.role == 'admin' %}或用户名{% endif %}...">
                        </div>

                        {% if user.role == 'admin' %}
                        <div class="col-md-3">
                            <label for="userFilter" class="form-label">用户筛选</label>
                            <select class="form-select" id="userFilter">
                                <option value="">所有用户</option>
                                <!-- 用户选项将通过JavaScript动态加载 -->
                            </select>
                        </div>
                        {% endif %}

                        <div class="col-md-{% if user.role == 'admin' %}2{% else %}3{% endif %}">
                            <label for="statusFilter" class="form-label">状态筛选</label>
                            <select class="form-select" id="statusFilter">
                                <option value="">所有状态</option>
                                <option value="active">活跃</option>
                                <option value="expired">已过期</option>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex align-items-end">
                            <button type="button" class="btn btn-outline-primary w-100" onclick="applyFilters()">
                                <i class="fas fa-search me-2"></i>筛选
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 分享列表 -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-light">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">
                            <i class="fas fa-list me-2"></i>
                            分享列表
                        </h5>
                        <span class="badge bg-primary" id="totalCount">0</span>
                    </div>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="sharesTable">
                            <thead class="table-light">
                                <tr>
                                    <th>网站/URL</th>
                                    <th>账号</th>
                                    {% if user.role == 'admin' %}
                                    <th>用户</th>
                                    {% endif %}
                                    <th>访问次数</th>
                                    <th>创建时间</th>
                                    <th>过期时间</th>
                                    <th>状态</th>
                                    <th class="text-center">操作</th>
                                </tr>
                            </thead>
                            <tbody id="sharesTableBody">
                                <!-- 数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="card-footer bg-light">
                    <div class="d-flex justify-content-between align-items-center">
                        <div id="sharesCount"></div>
                        <nav aria-label="Page navigation">
                            <ul class="pagination mb-0" id="pagination"></ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 查看访问日志模态框 -->
<div class="modal fade" id="viewLogsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-history me-2"></i>
                    访问日志
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="shareLogInfo"></div>
                <div class="table-responsive mt-4">
                    <table class="table table-hover mb-0">
                        <thead class="bg-light">
                            <tr>
                                <th scope="col">IP地址</th>
                                <th scope="col">用户代理</th>
                                <th scope="col">访问时间</th>
                            </tr>
                        </thead>
                        <tbody id="logsTableBody">
                            <!-- 日志数据将通过JavaScript加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal fade" id="deleteShareModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title text-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    确认删除
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要删除这个分享记录吗？</p>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    <strong>警告：</strong>此操作将同时删除相关的访问日志，且不可恢复！
                </div>
                <div id="deleteShareInfo" class="bg-light p-3 rounded">
                    <!-- 分享信息将在这里显示 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" onclick="confirmDeleteShare()">
                    <i class="fas fa-trash me-2"></i>
                    确认删除
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
let allShares = [];
let filteredShares = [];
let currentPage = 1;
const sharesPerPage = 10;
let currentShareId = null;

$(document).ready(function() {
    loadShares();
    {% if user.role == 'admin' %}
    loadUsers();
    {% endif %}

    // 搜索输入事件
    $('#searchInput').on('input', debounce(function() {
        applyFilters();
    }, 500));

    // 筛选器变化事件
    $('#statusFilter').on('change', function() {
        applyFilters();
    });

    {% if user.role == 'admin' %}
    $('#userFilter').on('change', function() {
        applyFilters();
    });
    {% endif %}
});

function loadShares() {
    const apiUrl = "{% if user.role == 'admin' %}/api/shares{% else %}/api/user/shares{% endif %}";
    
    $.ajax({
        url: apiUrl,
        method: 'GET',
        success: function(response) {
            allShares = response.shares;
            applyFilters();
        },
        error: function(xhr, status, error) {
            App.Utils.showAlert('加载分享列表失败: ' + error, 'danger');
        }
    });
}

{% if user.role == 'admin' %}
function loadUsers() {
    $.ajax({
        url: '/api/users',
        method: 'GET',
        success: function(response) {
            const userFilter = $('#userFilter');
            userFilter.find('option:not(:first)').remove();
            
            response.users.forEach(function(user) {
                userFilter.append(`<option value="${user.username}">${user.username}</option>`);
            });
        }
    });
}
{% endif %}

function applyFilters() {
    const searchTerm = $('#searchInput').val().toLowerCase();
    const statusFilter = $('#statusFilter').val();
    const userFilter = {% if user.role == 'admin' %}$('#userFilter').val(){% else %}''{% endif %};
    
    filteredShares = allShares.filter(function(share) {
        // 搜索过滤
        let matchesSearch = !searchTerm || 
            share.url.toLowerCase().includes(searchTerm) ||
            share.account.toLowerCase().includes(searchTerm);
            
        {% if user.role == 'admin' %}
        matchesSearch = matchesSearch || share.user_name.toLowerCase().includes(searchTerm);
        {% endif %}
        
        // 用户过滤
        let matchesUser = true;
        {% if user.role == 'admin' %}
        matchesUser = !userFilter || share.user_name === userFilter;
        {% endif %}
        
        // 状态过滤
        let matchesStatus = true;
        if (statusFilter === 'active') {
            matchesStatus = !share.is_expired;
        } else if (statusFilter === 'expired') {
            matchesStatus = share.is_expired;
        }
        
        return matchesSearch && matchesUser && matchesStatus;
    });
    
    renderSharesTable();
}

function renderSharesTable() {
    const startIndex = (currentPage - 1) * sharesPerPage;
    const endIndex = Math.min(startIndex + sharesPerPage, filteredShares.length);
    const pageShares = filteredShares.slice(startIndex, endIndex);
    
    const tableBody = $('#sharesTableBody');
    tableBody.empty();
    
    if (pageShares.length === 0) {
        tableBody.append(`
            <tr>
                <td colspan="{% if user.role == 'admin' %}8{% else %}7{% endif %}" class="text-center py-4">
                    <i class="fas fa-info-circle text-muted me-2"></i>
                    没有找到匹配的分享记录
                </td>
            </tr>
        `);
    } else {
        pageShares.forEach(function(share) {
            const statusBadge = share.is_expired ? 
                '<span class="badge bg-danger">已过期</span>' : 
                '<span class="badge bg-success">活跃</span>';
            
            const expireDate = share.expires_at ? 
                App.Utils.formatDateTime(share.expires_at) : '永不过期';
            
            const shortUrl = share.url.length > 30 ? share.url.substring(0, 30) + '...' : share.url;
            
            tableBody.append(`
                <tr ${share.is_expired ? 'class="table-warning"' : ''}>
                    <td title="${share.url}">${shortUrl}</td>
                    <td>${share.account}</td>
                    {% if user.role == 'admin' %}
                    <td><span class="badge bg-info">${share.user_name}</span></td>
                    {% endif %}
                    <td><span class="badge bg-primary">${share.access_count}</span></td>
                    <td>${App.Utils.formatDateTime(share.created_at)}</td>
                    <td>${expireDate}</td>
                    <td>${statusBadge}</td>
                    <td class="text-center">
                        <div class="btn-group btn-group-sm" role="group">
                            <button class="btn btn-outline-info" onclick="viewLogs(${share.id})" title="查看日志">
                                <i class="fas fa-chart-line"></i>
                            </button>
                            <button class="btn btn-outline-primary" onclick="copyShareLink('${share.share_token}')" title="复制链接">
                                <i class="fas fa-copy"></i>
                            </button>
                            <button class="btn btn-outline-danger" onclick="deleteShare(${share.id})" title="删除">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </td>
                </tr>
            `);
        });
    }
    
    // 更新计数
    $('#totalCount').text(filteredShares.length);
    $('#sharesCount').text(`显示 ${startIndex + 1} 到 ${endIndex} 条，共 ${filteredShares.length} 条记录`);
    
    // 更新分页
    renderPagination();
}

function renderPagination() {
    const totalPages = Math.ceil(filteredShares.length / sharesPerPage);
    const pagination = $('#pagination');
    pagination.empty();
    
    // 上一页
    pagination.append(`
        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage - 1})" aria-label="Previous">&laquo;</a>
        </li>
    `);
    
    // 页码
    for (let i = 1; i <= totalPages; i++) {
        pagination.append(`
            <li class="page-item ${i === currentPage ? 'active' : ''}">
                <a class="page-link" href="#" onclick="changePage(${i})">${i}</a>
            </li>
        `);
    }
    
    // 下一页
    pagination.append(`
        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="changePage(${currentPage + 1})" aria-label="Next">&raquo;</a>
        </li>
    `);
}

function changePage(page) {
    if (page < 1 || page > Math.ceil(filteredShares.length / sharesPerPage)) {
        return;
    }
    
    currentPage = page;
    renderSharesTable();
}

function viewLogs(shareId) {
    currentShareId = shareId;
    const baseUrl = "{% if user.role == 'admin' %}/api/shares/{% else %}/api/user/shares/{% endif %}";
    const apiUrl = baseUrl + shareId + "/logs";
    
    $.ajax({
        url: apiUrl,
        method: 'GET',
        success: function(response) {
            const logs = response.logs;
            const share = allShares.find(s => s.id === shareId);
            
            // 显示分享信息
            let shareInfoHtml = `
                <div class="bg-light p-3 rounded mb-2">
                    <div class="row">
                        <div class="col-sm-3"><strong>网站/URL：</strong></div>
                        <div class="col-sm-9 break-all">${share.url}</div>
                    </div>
                    <div class="row mt-1">
                        <div class="col-sm-3"><strong>账号：</strong></div>
                        <div class="col-sm-9">${share.account}</div>
                    </div>
                    <div class="row mt-1">
                        <div class="col-sm-3"><strong>分享链接：</strong></div>
                        <div class="col-sm-9 break-all">${window.location.origin}/share/${share.share_token}</div>
                    </div>`;
                    
                    {% if user.role == 'admin' %}
                    shareInfoHtml += `
                    <div class="row mt-1">
                        <div class="col-sm-3"><strong>用户：</strong></div>
                        <div class="col-sm-9">${share.user_name}</div>
                    </div>`;
                    {% endif %}
                     
                    shareInfoHtml += `
                </div>`;
                
                $('#shareLogInfo').html(shareInfoHtml);
            
            // 显示日志表格
            const tbody = $('#logsTableBody');
            tbody.empty();
            
            if (logs.length === 0) {
                tbody.append(`
                    <tr>
                        <td colspan="3" class="text-center py-4">
                            <i class="fas fa-info-circle text-muted me-2"></i>
                            暂无访问记录
                        </td>
                    </tr>
                `);
            } else {
                logs.forEach(function(log) {
                    const accessedAt = App.Utils.formatDateTime(log.accessed_at);
                    const shortUserAgent = log.user_agent ? 
                        (log.user_agent.length > 50 ? log.user_agent.substring(0, 50) + '...' : log.user_agent) : 
                        '-';
                    
                    tbody.append(`
                        <tr>
                            <td>${log.ip_address}</td>
                            <td title="${log.user_agent || ''}">${shortUserAgent}</td>
                            <td>${accessedAt}</td>
                        </tr>
                    `);
                });
            }
            
            $('#viewLogsModal').modal('show');
        },
        error: function(xhr, status, error) {
            App.Utils.showAlert('加载访问日志失败: ' + error, 'danger');
        }
    });
}

function copyShareLink(token) {
    const shareUrl = `${window.location.origin}/share/${token}`;
    navigator.clipboard.writeText(shareUrl).then(function() {
        App.Utils.showAlert('分享链接已复制到剪贴板', 'success');
    }).catch(function() {
        // 降级方案
        const textArea = document.createElement('textarea');
        textArea.value = shareUrl;
        document.body.appendChild(textArea);
        textArea.select();
        document.execCommand('copy');
        document.body.removeChild(textArea);
        App.Utils.showAlert('分享链接已复制到剪贴板', 'success');
    });
}

function deleteShare(shareId) {
    currentShareId = shareId;
    const share = allShares.find(s => s.id === shareId);
    
    // 显示分享信息
    $('#deleteShareInfo').html(`
        <div class="row">
            <div class="col-sm-3"><strong>网站/URL：</strong></div>
            <div class="col-sm-9 break-all">${share.url}</div>
        </div>
        <div class="row mt-1">
            <div class="col-sm-3"><strong>账号：</strong></div>
            <div class="col-sm-9">${share.account}</div>
        </div>
        {% if user.role == 'admin' %}
        <div class="row mt-1">
            <div class="col-sm-3"><strong>用户：</strong></div>
            <div class="col-sm-9">${share.user_name}</div>
        </div>
        {% endif %}
    `);
    
    $('#deleteShareModal').modal('show');
}

function confirmDeleteShare() {
    if (!currentShareId) return;
    
    const baseUrl = "{% if user.role == 'admin' %}/api/shares/{% else %}/api/user/shares/{% endif %}";
    const apiUrl = baseUrl + currentShareId;
    
    $.ajax({
        url: apiUrl,
        method: 'DELETE',
        success: function(response) {
            App.Utils.showAlert('分享已成功删除', 'success');
            $('#deleteShareModal').modal('hide');
            loadShares(); // 重新加载分享列表
        },
        error: function(xhr, status, error) {
            App.Utils.showAlert('删除分享失败: ' + error, 'danger');
        }
    });
}

{% if user.role == 'admin' %}
function exportShares() {
    window.open('/api/export/shares', '_blank');
}
{% endif %}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function() {
        const context = this;
        const args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(context, args), wait);
    };
}
</script>
{% endblock %}

{% block extra_css %}
<style>
.table-warning {
    --bs-table-bg: #fff3cd;
}

.btn-group-sm .btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
}

.badge {
    font-size: 0.75em;
}

.break-all {
    word-break: break-all;
}
</style>
{% endblock %}